const http = require('http');

const API_BASE = 'http://localhost:3000/api';

function makeRequest(url, options = {}) {
  return new Promise((resolve, reject) => {
    const requestOptions = {
      method: options.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    };

    const req = http.request(url, requestOptions, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          resolve({
            status: res.statusCode,
            data: jsonData
          });
        } catch (e) {
          resolve({
            status: res.statusCode,
            data: data
          });
        }
      });
    });

    req.on('error', (error) => {
      console.error('请求错误:', error.message);
      reject(error);
    });
    
    if (options.body) {
      req.write(options.body);
    }
    
    req.end();
  });
}

async function testTaskUpdateFix() {
  console.log('🧪 测试任务更新修复...\n');

  let testTaskId = null;

  try {
    // 1. 创建测试任务
    console.log('1️⃣ 创建测试任务...');
    const createResponse = await makeRequest(`${API_BASE}/tasks`, {
      method: 'POST',
      body: JSON.stringify({
        title: '测试任务更新',
        description: '用于测试更新功能的任务',
        priority: 'P1',
        category: 'work',
        completed: false
      })
    });

    if (createResponse.status === 201) {
      testTaskId = createResponse.data.id;
      console.log(`   ✅ 任务创建成功，ID: ${testTaskId}`);
    } else {
      console.log(`   ❌ 任务创建失败: ${JSON.stringify(createResponse.data)}`);
      return;
    }

    // 2. 测试切换任务状态（使用新的toggle API）
    console.log('\n2️⃣ 测试切换任务状态...');
    const toggleResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}/toggle`, {
      method: 'PATCH'
    });

    if (toggleResponse.status === 200) {
      console.log(`   ✅ 任务状态切换成功: ${toggleResponse.data.message}`);
    } else {
      console.log(`   ❌ 任务状态切换失败: ${JSON.stringify(toggleResponse.data)}`);
    }

    // 3. 验证任务状态已更新
    console.log('\n3️⃣ 验证任务状态...');
    const getResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}`);

    if (getResponse.status === 200) {
      console.log(`   ✅ 任务获取成功`);
      console.log(`   📋 任务标题: ${getResponse.data.title}`);
      console.log(`   ✅ 完成状态: ${getResponse.data.completed ? '已完成' : '未完成'}`);
    } else {
      console.log(`   ❌ 任务获取失败: ${JSON.stringify(getResponse.data)}`);
    }

    // 4. 测试完整任务更新
    console.log('\n4️⃣ 测试完整任务更新...');
    const updateResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}`, {
      method: 'PUT',
      body: JSON.stringify({
        title: '已更新的测试任务',
        description: '更新后的描述',
        priority: 'P2',
        category: 'personal',
        tags: ['测试', '更新'],
        notes: '测试备注'
      })
    });

    if (updateResponse.status === 200) {
      console.log(`   ✅ 任务更新成功: ${updateResponse.data.message}`);
    } else {
      console.log(`   ❌ 任务更新失败: ${JSON.stringify(updateResponse.data)}`);
    }

    // 5. 测试空标题更新（应该失败）
    console.log('\n5️⃣ 测试空标题更新（应该失败）...');
    const emptyTitleResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}`, {
      method: 'PUT',
      body: JSON.stringify({
        title: '',
        description: '空标题测试'
      })
    });

    if (emptyTitleResponse.status === 400) {
      console.log(`   ✅ 空标题验证成功: ${emptyTitleResponse.data.error}`);
    } else {
      console.log(`   ❌ 空标题验证失败，应该返回400错误: ${JSON.stringify(emptyTitleResponse.data)}`);
    }

    // 清理
    if (testTaskId) {
      console.log('\n🧹 清理测试数据...');
      const deleteResponse = await makeRequest(`${API_BASE}/tasks/${testTaskId}`, {
        method: 'DELETE'
      });

      if (deleteResponse.status === 200) {
        console.log(`   ✅ 测试任务删除成功`);
      } else {
        console.log(`   ❌ 测试任务删除失败: ${JSON.stringify(deleteResponse.data)}`);
      }
    }

  } catch (error) {
    console.error('❌ 测试过程中出现错误:', error);
    console.error('错误详情:', error.message);
  }

  console.log('\n🎉 任务更新修复测试完成!');
}

if (require.main === module) {
  testTaskUpdateFix().catch(console.error);
}

module.exports = { testTaskUpdateFix };
